<template>
  <van-cell
    v-if="songInfo && songInfo.ar"
    value="内容"
    :title="`${songInfo.name}-${songInfo.ar[0].name}`"
    class="cell"
    :border="true"
  >
    <!-- 使用 title 插槽来自定义标题 -->
    <template #icon>
      <div class="play">
        <!-- 留声机 - 容器 -->
        <div class="song-wrapper">
          <!-- 留声机本身(靠css动画做旋转) -->
          <div
            class="song-turn ani"
            :style="`animation-play-state:${playState ? 'running' : 'paused'}`"
          >
            <div class="song-img">
              <!-- &&写法是为了防止报错, 有字段再继续往下访问属性 -->
              <img
                style="width: 100%"
                :src="`${
                  songInfo && songInfo.al && songInfo.al.picUrl
                }?imageView&thumbnail=360y360&quality=75&tostatic=0`"
                alt=""
              />
            </div>
          </div>
          <!-- 播放歌词容器 -->
        </div>
        <!-- 播放音乐真正的标签
      看接口文档: 音乐地址需要带id去获取(但是有的歌曲可能404)
      https://binaryify.github.io/NeteaseCloudMusicApi/#/?id=%e8%8e%b7%e5%8f%96%e9%9f%b3%e4%b9%90-url
     -->
        <audio
          ref="audio"
          preload="true"
          :src="`https://music.163.com/song/media/outer/url?id=${id}.mp3`"
        ></audio>
      </div>
    </template>
    <template #default>
      <!-- 播放 -->
      <span
        class="iconfont icon-bofang"
        @click.stop="audioStart"
        v-show="!playState"
      ></span>
      <!-- 暂停 -->
      <span
        class="iconfont icon-caozuo-bofang-zanting"
        @click.stop="audioStart"
        v-show="playState"
      ></span>
    </template>
  </van-cell>
</template>

<script>
// 获取歌曲详情和 歌曲的歌词接口
// import { getSongByIdAPI, getLyricByIdAPI } from '@/api'
import { Icon } from "vant";
export default {
  components: {
    [Icon.name]: Icon,
  },
  name: "play",
  data () {
    return {
      playState: false, // 音乐播放状态(true暂停, false播放)
      songInfo: {}, // 歌曲信息
      lyric: {}, // 歌词枚举对象(需要在js拿到歌词写代码处理后, 按照格式保存到这个对象)
      curLyric: "", // 当前显示哪句歌词
      lastLy: "", // 记录当前播放歌词
      sumTime: '00:00',
      nowTime: '00:00',
      nowTimePercentage: '',
    };
  },
  watch: {
    playState (v) {
      this.$store.commit('setPlayState', v)

    },
    Progress (a) {
      this.$refs.audio.currentTime = a
      // this.ct = this.$refs.audio.currentTime;
    },
    AplayState () {
      if (!this.playState) {
        // 如果状态为false
        this.$refs.audio.play(); // 调用audio标签的内置方法play可以继续播放声音
      } else {
        this.$refs.audio.pause(); // 暂停audio的播放
      }
      this.playState = !this.playState; // 点击设置对立状态
    },
    playNum () {
      this.$nextTick(() => {
        this.$refs.audio.play()
        this.playState = true
      })
    }

  },
  computed: {
    needleDeg () {
      // 留声机-唱臂的位置属性
      return this.playState ? "-7deg" : "-38deg";
    },
    Progress () { return this.$store.state.Progress },
    AplayState () { return this.$store.state.AplayState },
    playNum () { return this.$store.state.playNum },
    id () { return this.$store.state.id || this.$store.state.List[0].id }
  },
  methods: {
    // 下一曲
    async nextG () {
      this.nowTimePercentage = 0
      this.$store.commit('nextId', this.id)
      this.id = this.$store.state.nextId
      await this.getSong()
      this.playState = false
      this.audioStart()
    },
    // 上一曲
    async preveG () {
      this.nowTimePercentage = 0
      this.$store.commit('preveId', this.id)
      this.id = this.$store.state.nextId
      await this.getSong()
      this.playState = false
      this.audioStart()
    },
    async getSong () {
      // 获取歌曲详情, 和歌词方法
      // const res = await getSongByIdAPI(this.id)
      const res = await this.axios({
        url: `/song/detail?ids=${this.id}`,
      });

      this.songInfo = res.data.songs[0];
      this.$store.commit('setSongInfo', this.songInfo)
      // 获取-并调用_formatLyr方法, 处理歌词
      // const lyrContent = await getLyricByIdAPI(this.id)

      const lyrContent = await this.axios({
        url: `/lyric?id=${this.id}`,
      });

      const lyricStr = lyrContent.data.lrc.lyric;
      this.lyric = this._formatLyr(lyricStr);
      this.$store.commit('setLyric', this.lyric)
      // 初始化完毕先显示零秒歌词
      this.curLyric = this.lyric[0];
      this.$store.commit('setCurLyric', this.curLyric)
    },
    _formatLyr (lyricStr) {
      // 可以看network观察歌词数据是一个大字符串, 进行拆分.
      let reg = /\[.+?\]/g; //
      let timeArr = lyricStr.match(reg); // 匹配所有[]字符串以及里面的一切内容, 返回数组
      // console.log(timeArr); // ["[00:00.000]", "[00:01.000]", ......]
      let contentArr = lyricStr.split(/\[.+?\]/).slice(1); // 按照[]拆分歌词字符串, 返回一个数组(下标为0位置元素不要,后面的留下所以截取)
      let lyricObj = {}; // 保存歌词的对象, key是秒, value是显示的歌词
      timeArr.forEach((item, index) => {
        // 拆分[00:00.000]这个格式字符串, 把分钟数字取出, 转换成秒
        let ms = item.split(":")[0].split("")[2] * 60;
        // 拆分[00:00.000]这个格式字符串, 把十位的秒拿出来, 如果是0, 去拿下一位数字, 否则直接用2位的值
        let ss =
          item.split(":")[1].split(".")[0].split("")[0] === "0"
            ? item.split(":")[1].split(".")[0].split("")[1]
            : item.split(":")[1].split(".")[0];
        // 秒数作为key, 对应歌词作为value
        lyricObj[ms + Number(ss)] = contentArr[index];
      });
      // 返回得到的歌词对象(可以打印看看)
      // console.log(lyricObj);
      return lyricObj;
    },
    audioStart () {
      // 播放按钮 - 点击事件
      if (!this.playState) {
        // 如果状态为false
        this.$refs.audio.play(); // 调用audio标签的内置方法play可以继续播放声音
      } else {
        this.$refs.audio.pause(); // 暂停audio的播放
      }
      this.playState = !this.playState; // 点击设置对立状态
    },
    showLyric () {
      // 监听播放audio进度, 切换歌词显示

      if (this.$refs.audio) {
        this.$refs.audio.addEventListener("timeupdate", () => {
          let curTime = Math.floor(this.$refs.audio.currentTime);
          // 避免空白出现
          this.sumTime = this.momentTime(this.$refs.audio.duration)
          this.$store.commit('setDuration', this.$refs.audio.duration)
          this.$store.commit('setSumTime', this.sumTime)
          this.nowTime = this.momentTime(this.$refs.audio.currentTime)
          this.$store.commit('setNowTime', this.nowTime)
          this.nowTimePercentage = parseInt((this.$refs.audio.currentTime / this.$refs.audio.duration) * 100)
          this.$store.commit('setNowTimePercentage', this.nowTimePercentage)
          // console.log(this.$refs.audio.duration)
          if (this.lyric[curTime]) {
            this.curLyric = this.lyric[curTime];
            this.$store.commit('setCurLyric', this.lyric[curTime])
            this.lastLy = this.curLyric;
            this.$store.commit('setLastLy', this.lastLy)
          } else {
            this.curLyric = this.lastLy;
            this.$store.commit('setCurLyric', this.lastLy)
          }
        });
        this.$refs.audio.loop = false;
        this.$refs.audio.addEventListener('ended', () => {
          this.audioStart()
          this.audioStart()
        }, false);
      }

    },
    momentTime (a) {
      let m = parseInt(a / 60 % 60)
      let s = parseInt(a % 60)
      return '0' + m + ':' + (s > 9 ? s : '0' + s)

    }
  },
  mounted () {
    this.getSong();
    this.showLyric();
    // console.log(this.$route.query.id);
  },
  updated () {
    this.showLyric();


  }

};
</script>

<style scoped>
/* 播放 */
.icon-bofang {
  /* position: fixed;
  left: 165px;
  bottom: 90px; */
  color: #333;
  height: 30px;
  margin-top: -10px;
  font-size: 30px;
  z-index: 1000000;
}
/* 暂停 */
.icon-caozuo-bofang-zanting {
  /* position: fixed;
  left: 165px;
  bottom: 90px; */
  color: #333;
  height: 30px;
  margin-top: -10px;
  font-size: 30px;
  z-index: 1000000;
}
.van-cell__value {
  text-align: right;
  line-height: 30px;
}
.song-wrapper {
  width: 40px;
  height: 40px;
  left: 0;
  top: 0;

  z-index: 10001;
  margin-right: 10px;
}
.song-turn {
  width: 100%;
  height: 100%;
  background: url('./img/bg.png') no-repeat;
  background-size: 100%;
}

.song-img {
  width: 62%;
  height: 62%;
  position: absolute;
  left: 50%;
  top: 50%;
  overflow: hidden;
  border-radius: 50%;
  transform: translate(-50%, -50%);
}

.ani {
  animation: turn 5s linear infinite;
}
@keyframes turn {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}
.cell {
  height: 50px;
}
</style>